use std::{sync::Arc, thread::JoinHandle, time::Duration};

use crossbeam::channel::{bounded, Receiver};

// use kanal::{bounded, Receiver};

use crate::vec::{ReadGuard, SyncVec};

pub struct CachePackage<T: Default> {
    list: Arc<SyncVec<T>>,
    receiver_index: Receiver<usize>,
    _thread_join: JoinHandle<()>,
}

impl<T: Default + 'static> CachePackage<T> {
    pub fn new(cap: usize, mem_size: usize) -> Self {
        let list = Arc::new(SyncVec::new());
        let list_c = list.clone();
        let (tx, rx) = bounded(cap);
        // let (tx, rx) = crossbeam::channel::bounded(cap);
        if mem_size < 1024 {
            debug!("cache_package mem_size: {} bt", mem_size);
        } else if mem_size < 1024 * 1024 {
            debug!("cache_package mem_size: {:.2} kb", mem_size as f64 / 1024.0);
        } else {
            debug!(
                "cache_package mem_size: {:.2} mb",
                mem_size as f64 / 1024.0 / 1024.0
            );
        }
        let _thread_join = std::thread::Builder::new()
            .stack_size(mem_size)
            .spawn(move || loop {
                let i = list_c.push_return(T::default());
                if let Err(_e) = tx.send(i) {
                    error!("cache_package tx.send error[{i}]: {_e}");
                    #[cfg(debug_assertions)]
                    println!("cache_package tx.send error[{i}]: {_e}");
                    std::thread::sleep(std::time::Duration::from_secs(1));
                }
            })
            .unwrap();
        Self { list, receiver_index: rx, _thread_join }
    }

    #[inline(always)]
    pub fn next(&self) -> ReadGuard<'_, T> {
        let i = self.receiver_index.recv().unwrap_or_else(|_e| {
            let i = self.list.push_return(T::default());
            warn!("cache_package.try_recv error[{i}]: {_e}");
            i
        });
        self.list.get_uncheck(i)
    }
}

/*
mod test {

    /// 提前生成的缓存，在使用申请缓存即可, 必竟要生成一个3千元素的数组需要100微秒
    /// 提前生成10个
    /// 使用: 行情_缓存.try_recv()
    static 行情_缓存: StaticType<CachePackage<List_高频数据<QTY_前后封单_行情端, 3000>>> = StaticType::new();

    pub fn init_static() -> IResult {
        行情_缓存.init_call(|| CachePackage::new(3001));
        Ok(())
    }

    #[test]
    fn test_static_data() {
        std::thread::Builder::new()
            .stack_size(1024 * 1204 * 1024)
            .spawn(|| {
                init_static().unwrap();
                std::thread::sleep(Duration::from_secs(3));

                let count = 2000;
                let mut time_elapse = Duration::from_micros(0);

                for _ in 0..count {
                    let start = std::time::Instant::now();
                    let list = 行情_缓存.next();
                    list.push(Default::default());
                    list.push(Default::default());
                    time_elapse += start.elapsed();
                }

                println!("计算次数 {count}, 平均耗时: {:?}", time_elapse / count);
            })
            .unwrap()
            .join()
            .unwrap();
    }
}
*/
